//
//  AuctionOrderDetail.swift
//  LeGou
//
//  Created by lxm on 2022/10/17.
//

import UIKit

class CompoundOrderDetail: ZMViewController {
    //MARK: --------------------属性--------------------
    var conflateId = 0
    
    var orderInfo = ZMUtil.fastNilBehavior(type: OrderDetail.self)
    
    let timer = Observable<Int>.timer(.seconds(0), period: .milliseconds(10), scheduler: MainScheduler.instance)
    
    var timerDisposeBag = DisposeBag()
    
    var bindDisposeBag = DisposeBag()
    //MARK: --------------------UI控件--------------------
    let nav = NavigationBarView()
    
    let scrollView = UIScrollView()

    let scrollContent = ZMUtil.stackView(axis: .vertical, spacing: 8)

    let bgView = UIView().then({$0.backgroundColor = Style.mainColor})
    
    let scrollBgView = UIView().then({$0.backgroundColor = Style.mainColor})

    // 状态背景
    let stateBg = ZMUtil.imageView(imageName: "order_bag_bg")
    
    let header = OrderDetailHeaderView()
        
    // 商品信
    
    let compoundGoodsView = CompoundGoodsView()
    
    let info = DetailInfoView()
    
    let bottomView = UIView().then({$0.backgroundColor = .white})
    
    let leftButton = UIButton()
    
    let rightButton = UIButton()
    
    let loading = XMLoadingView()
    
    let auctionListView = CompoundDetailBottomListView()
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loading.showInView(fatherView: view)
        loadDetail()
    }
    
    //MARK: --------------------UI--------------------
    func setUI() {
        hbd_barHidden = true
        view.addSubview(bgView)
        
        view.addSubview(nav)
        nav.autoBack = true
        
        view.addSubview(scrollView)
        
        scrollView.addSubview(scrollBgView)
        
        scrollView.addSubview(stateBg)
        
        scrollView.layer.masksToBounds = false
        
        scrollView.addSubview(scrollContent)
        
        scrollContent.addArrangedSubview(header)
                        
        scrollContent.addArrangedSubview(compoundGoodsView)
        
        scrollContent.addArrangedSubview(info)
        
        scrollContent.addArrangedSubview(auctionListView)
        
        compoundGoodsView.onLayoutSubviews = { [weak compoundGoodsView] in
            if let compoundGoodsView = compoundGoodsView  {
                ZMUtil.clipCircle(view: compoundGoodsView, Corner: [.topLeft, .topRight], radius: 12)
            }
        }
        
        scrollView.backgroundColor = "#F5F5F5".zm.hex()
        
        view.addSubview(bottomView)
        
        // bottom button
        setBottomButtonStyle(leftButton, 0, "联系客服")
        setBottomButtonStyle(rightButton, 1, "确认收货")
        
        let stack = ZMUtil.stackView(axis: .horizontal, spacing: 12)
        stack.addArrangedSubview(leftButton)
        stack.addArrangedSubview(rightButton)
        bottomView.addSubview(stack)
        stack.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-16)
        }
    }
    
    func addConstraints() {
        scrollBgView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(80)
        }
        nav.snp.makeConstraints { make in
            make.top.right.left.equalToSuperview()
        }
        
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(nav.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top)
        }
        
        scrollContent.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        
        bgView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(400)
        }
        
        stateBg.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(-30)
        }
        
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(56)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
    }
    
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        orderInfo.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            self.bindDisposeBag = DisposeBag()
            
            // 是否有效
            let validFlag = resp.conflateStatus != 2
            if validFlag {
                info.info = [
                    ("开始时间：", resp.createTime, nil),
                    ("合成时间：", resp.conflateTime, nil),
                    ("奖励金额：", "￥\(resp.refundAmount.zm.toString(keep: 4))", "#DE3F26".zm.hex()),
                ]
                if resp.extraAmount  > 0 {
                    info.info.append(("额外奖励：", "￥\(resp.extraAmount.zm.toString(keep: 4))", "#DE3F26".zm.hex()))
                }
                info.info.append(("合计金额：", "￥\(resp.totalAmount.zm.toString(keep: 4))", "#DE3F26".zm.hex()))
                if resp.giveQuantity > 0 {
                    info.info.append(("赠送数量：", "\(resp.giveQuantity)件", nil))
                }
            } else {
                info.info = [
                    ("开始时间：", resp.createTime, nil),
                    ("失效时间：", resp.expTime, nil),
                    ("返还金额：", "￥\(resp.refundAmount.zm.toString(keep: 4))", "#DE3F26".zm.hex())
                ]
            }
            
            self.header.statusIcon.image = validFlag ? UIImage.init(named: "compound_order_success") : UIImage.init(named: "order_close_icon")
            self.header.statusLabel.text = validFlag ? "合成成功" : "已失效"
            self.header.hidePayButton()
            self.header.subTitle.text = validFlag ? "" : "超时未完成合成"
            self.stateBg.image = validFlag ? UIImage.init(named: "order_bag_bg") : UIImage.init(named: "order_close_bg")

            // goodsView
            self.compoundGoodsView.img.zm.setImage(urlStr: resp.image)
            self.compoundGoodsView.name.text = resp.productName
            self.compoundGoodsView.price.text = "合成商品数量：\(resp.currentTotal)"
            
            self.leftButton.isHidden = true
            self.rightButton.isHidden = false
            if (resp.orderId.count == 0 || !validFlag) {
                self.bottomView.isHidden = true
                self.scrollView.snp.remakeConstraints { make in
                    make.top.equalTo(nav.snp.bottom)
                    make.left.right.equalToSuperview()
                    make.bottom.equalToSuperview()
                }
            } else {
                self.bottomView.isHidden = false
                self.scrollView.snp.remakeConstraints { make in
                    make.top.equalTo(nav.snp.bottom)
                    make.left.right.equalToSuperview()
                    make.bottom.equalTo(bottomView.snp.top)
                }
            }
            
            self.setBottomButtonStyle(self.rightButton, 1, "赠送商品订单")
            self.rightButton.rx.tap.subscribe(onNext:{ [unowned self] r in
                let order = resp.orderId
                let vc = VIPOrderDetail()
                vc.orderNo = order
                self.navigationController?.pushViewController(vc, animated: true)
            }).disposed(by: bindDisposeBag)
            self.auctionListView.listData = resp.afterListResponseList.map({("\($0.ahCount)", "¥\($0.currentPrice.zm.toString(keep: 4))", ($0.conflateRefundStatus == 0 ? "¥0" : "¥\($0.currentPrice.zm.toString(keep: 4))"))})
        }).disposed(by: disposeBag)
    }
    
    func loadDetail() {
        AuctionAPI.compoundDetail(["conflateId" : conflateId]).rxRequest(type: OrderDetail.self).subscribe(onNext:{ [unowned self] resp in
            self.loading.hideView(anmation: true)
            self.orderInfo.accept(resp)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    func setBottomButtonStyle(_ button : UIButton, _ type : Int, _ title : String) {
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        button.layer.cornerRadius = 16
        button.snp.remakeConstraints { make in
            make.height.equalTo(32)
        }
        button.setTitle(title, for: .normal)
        button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)

        if type == 0 {
            button.layer.borderWidth = 0.5
            button.layer.borderColor = "#CCCCCC".zm.hex().cgColor
            button.backgroundColor = .white
            button.setTitleColor(UIColor.zm.color333333(), for: .normal)
        } else {
            button.layer.borderWidth = 0
            button.backgroundColor = Style.mainColor
            button.setTitleColor(.white, for: .normal)
        }
    }
    //MARK: --------------------delegate--------------------
}


extension CompoundOrderDetail {
    struct OrderDetail : HandyJSON {
        var afterListResponseList = [GoodsList]()
        var conflateTime = ""
        var createTime = ""
        var currentTotal = 0
        var expTime = ""
        var extraAmount = 0.0
        var giveQuantity: Int = 0
        var id: Int = 0
        var image = ""
        var orderId = ""
        var productId: Int = 0
        var productName = ""
        var refundAmount = 0.0
        var totalAmount = 0.0
        // 状态（0：合成中、1：合成成功、2：合成失效）
        var conflateStatus = 0
    }
    
    struct GoodsList : HandyJSON {
        var ahCount: Int = 0
        var auctionId: Int = 0
        var conflateId: Int = 0
        var conflateRefundStatus: Int = 0
        var currentPrice = 0.0
        var image = ""
        var oid: Int = 0
        var orderId = ""
        var productName = ""
        var state: Int = 0
        var stockState: Int = 0
    }
}
